package com.chen.palmar.project.set;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chen.palmar.R;
import com.chen.palmar.base.BaseActivity;
import com.chen.palmar.common.datasource.DataCenter;
import com.chen.palmar.common.override.HttpSubscriber;
import com.chen.palmar.common.widget.dialog.SelectPickerDialog;
import com.chen.palmar.common.widget.view.AutoToolbar;
import com.chen.palmar.common.widget.view.CircleImageView;
import com.chen.palmar.entity.EditShopEntity;
import com.chen.palmar.entity.SetShopEntity;
import com.chen.palmar.entity.ShopInfoRequest;
import com.chen.palmar.entity.TagListEntity;
import com.chen.palmar.project.agency.CityPickerActivity;
import com.primb.androidlibs.net.entity.HttpResultEntity;
import com.primb.androidlibs.net.entity.MessageEvent;
import com.squareup.picasso.Picasso;
import com.zaaach.citypicker.model.City;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import io.valuesfeng.picker.ImageSelectActivity;
import io.valuesfeng.picker.Picker;
import io.valuesfeng.picker.engine.GlideEngine;
import io.valuesfeng.picker.engine.PicassoEngine;
import rx.Observable;
import rx.Subscription;

/**
 * Created by chen on 2018/1/12.
 */

public class EditShopActivity extends BaseActivity {
    private static final int REQUEST_CODE_IMG = 41;
    public static final int EVENT_SHOP_CODE = 1;
    @Bind(R.id.title_bar)
    TextView titleBar;
    @Bind(R.id.tool_bar)
    AutoToolbar toolBar;
    @Bind(R.id.iv_shop_head)
    CircleImageView ivShopHead;
    @Bind(R.id.et_shop_desc)
    EditText etShopDesc;
    @Bind(R.id.et_shop_name)
    EditText etShopName;
    @Bind(R.id.et_shop_user_name)
    EditText etShopUserName;
    @Bind(R.id.et_shop_phone)
    EditText etShopPhone;
    @Bind(R.id.tv_shop_tag)
    TextView tvShopTag;
    @Bind(R.id.tv_shop_address)
    TextView tvShopAddress;
    @Bind(R.id.et_shop_brand)
    EditText etShopBrand;
    @Bind(R.id.ly_store_manager)
    LinearLayout lyStoreManager;
    @Bind(R.id.tv_shop_name)
    TextView tvShopName;
    @Bind(R.id.ly_shop_name)
    LinearLayout lyShopName;
    private ShopInfoRequest request;
    private String factoryId;
    private SetShopEntity.DataBean entity;
    private Uri uri;
    private static final int REQUEST_CODE_PICK_CITY = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    @Override
    public void init() {
        toolBar.setNavigationOnClickListener(v -> EditShopActivity.this.finish());

        titleBar.setText("店铺编辑");

        request = new ShopInfoRequest();

        factoryId = getIntent().getStringExtra("factoryId");

        entity = (SetShopEntity.DataBean) getIntent().getSerializableExtra("entity");

        request.setCategory_id(entity.getCategory_id() + "");

        request.setCategoryName(getIntent().getStringExtra("name"));

        request.setStoreId(entity.getStores().getSotreId() + "");

        lyStoreManager.setVisibility(View.VISIBLE);

        lyShopName.setVisibility(View.GONE);

        tvShopName.setVisibility(View.VISIBLE);

        Picasso.with(this).load(R.mipmap.set_head_icon).placeholder(R.mipmap.set_head_icon).error(R.mipmap.set_head_icon).into(ivShopHead);

        getDataForWeb(entity.getStores().getSotreId());
    }

    private void getDataForWeb(int sotreId) {
        HashMap<String, String> map = new HashMap<>();
        map.put("storeId", sotreId + "");
        Subscription subscribe = DataCenter.editShopInfo(map).subscribe(new HttpSubscriber<EditShopEntity>(this, showLoading()) {
            @Override
            public void onNext(EditShopEntity editShopEntity) {
                EditShopEntity.DataBean data = editShopEntity.getData();
                Picasso.with(EditShopActivity.this).load(data.getLogo()).placeholder(R.mipmap.set_head_icon).error(R.mipmap.set_head_icon).into(ivShopHead);
                tvShopAddress.setText(data.getAddress_name());
                request.setAddress_id(data.getAddress_id() + "");
                etShopBrand.setText(data.getProduct());
                etShopDesc.setText(data.getDesc());
                etShopUserName.setText(data.getContacts());
                etShopPhone.setText(data.getMobile());
                tvShopTag.setText(data.getLabelName());
                request.setFactory_id(factoryId);
                tvShopName.setText(data.getName());
                request.setName(data.getName());
                request.setAddress_id(data.getAddress_id() + "");
                request.setCategoryName(data.getCategoryName());
            }
        });
        subscription.add(subscribe);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_apply_shop;
    }

    @OnClick({R.id.iv_shop_head, R.id.tv_shop_tag, R.id.tv_shop_store, R.id.tv_shop_address, R.id.btn_apply_info})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_shop_tag:
                showTagDialog();
                break;
            case R.id.iv_shop_head:
                Picker.from(this).singleChoice().enableCamera(true).setEngine(new GlideEngine()).forResult(REQUEST_CODE_IMG);
                break;
            case R.id.tv_shop_store:
                Intent intent = new Intent(this, StoreManagerActivity.class);
                intent.putExtra("info", entity.getStores().getSotreId() + "");
                startActivity(intent);
                break;
            case R.id.tv_shop_address:
                startActivityForResult(new Intent(this, CityPickerActivity.class), REQUEST_CODE_PICK_CITY);
                break;
            case R.id.btn_apply_info:
                applyInfo();
                break;
        }
    }

    private void showTagDialog() {
        SelectPickerDialog<TagListEntity.DataBean> dialog = new SelectPickerDialog<>();
        dialog.setListener(new SelectPickerDialog.OnPickedListener<TagListEntity.DataBean>() {
            @Override
            public void onPickCompleted(TagListEntity.DataBean dataDesc) {
                request.setLabel_id(dataDesc.getLabelId() + "");
                tvShopTag.setText(dataDesc.getName());
            }
        });
        dialog.show(getSupportFragmentManager());
        getTagList(dialog);
    }

    private void getTagList(SelectPickerDialog dialog) {
        Subscription subscribe = DataCenter.tagListInfo().subscribe(new HttpSubscriber<TagListEntity>(this, null) {
            @Override
            public void onNext(TagListEntity tagListEntity) {
                if (null != dialog && dialog.isVisible()) {
                    dialog.setDateList(tagListEntity.getData());
                }
            }
        });
        subscription.add(subscribe);
    }

    private void applyInfo() {
        request.setContacts(etShopUserName.getText().toString());
        request.setMobile(etShopPhone.getText().toString());
        request.setDesc(etShopDesc.getText().toString());
        request.setFactory_id(factoryId);
        request.setProduct(etShopBrand.getText().toString());
        if (!checkParams()) {
            return;
        }
        Observable<HttpResultEntity> shopInfo;
        if (uri != null) {
            shopInfo = DataCenter.updateShopInfo(request, uri);
        } else {
            shopInfo = DataCenter.updateShopInfo(request);
        }
        Subscription subscribe = shopInfo.subscribe(new HttpSubscriber<HttpResultEntity>(this, showLoading("发布中")) {

            @Override
            public void onNext(HttpResultEntity entity) {
                showToast(entity.getMessage());
                EventBus.getDefault().post(new MessageEvent(EVENT_SHOP_CODE));
                EditShopActivity.this.finish();
            }
        });
        subscription.add(subscribe);
    }

    private boolean checkParams() {
        if (TextUtils.isEmpty(request.getCategory_id())) {
            showToast("请选择店铺分类");
            return false;
        } else if (TextUtils.isEmpty(request.getFactory_id())) {
            showToast("厂家身份id为空，请退出重试");
            return false;
        } else {
            return true;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_IMG && resultCode == Activity.RESULT_OK) {
            List<Uri> imgList = data.getParcelableArrayListExtra(ImageSelectActivity.EXTRA_RESULT_SELECTION);
            uri = imgList.get(0);
            Picasso.with(this).load(uri).placeholder(R.mipmap.set_head_icon).error(R.mipmap.set_head_icon).into(ivShopHead);
        } else if (requestCode == REQUEST_CODE_PICK_CITY && resultCode == RESULT_OK) {
            if (data != null) {
                City city = (City) data.getSerializableExtra(CityPickerActivity.KEY_PICKED_CITY);
                tvShopAddress.setText(city.getName());
                request.setAddress_id(city.getAddessId() + "");
            }
        }
    }
}
